import { versionModel, scriptModel, type IVersion, type VersionDiff } from '../database/models';

export interface CreateVersionData {
  script_id: string;
  content: string;
  message?: string;
  author?: string;
  parent_version?: string;
}

export class VersionService {
  // 创建新版本
  async createVersion(data: CreateVersionData): Promise<IVersion> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(data.script_id);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    // 检查内容是否有变化
    const crypto = require('crypto');
    const contentHash = crypto.createHash('sha256').update(data.content).digest('hex');
    
    const contentExists = await versionModel.isContentExists(data.script_id, contentHash);
    if (contentExists) {
      throw new Error('内容未发生变化，无需创建新版本');
    }
    
    // 验证父版本
    if (data.parent_version) {
      const parentVersion = await versionModel.findById(data.parent_version);
      if (!parentVersion || parentVersion.script_id !== data.script_id) {
        throw new Error('父版本不存在或不属于该脚本');
      }
    }
    
    // 创建版本
    return await versionModel.createVersion(data);
  }
  
  // 获取版本历史
  async getVersionHistory(scriptId: string, options: {
    limit?: number;
    offset?: number;
  } = {}): Promise<{
    versions: IVersion[];
    total: number;
    page: number;
    pageSize: number;
  }> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    const limit = options.limit || 20;
    const offset = options.offset || 0;
    const page = Math.floor(offset / limit) + 1;
    
    const versions = await versionModel.getVersionHistory(scriptId, options);
    const total = await versionModel.count({ script_id: scriptId });
    
    return {
      versions,
      total,
      page,
      pageSize: limit
    };
  }
  
  // 获取特定版本
  async getVersion(scriptId: string, version: string): Promise<IVersion | null> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    return await versionModel.getVersion(scriptId, version);
  }
  
  // 获取版本详情
  async getVersionById(versionId: string): Promise<IVersion | null> {
    return await versionModel.findById(versionId);
  }
  
  // 获取最新版本
  async getLatestVersion(scriptId: string): Promise<IVersion | null> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    return await versionModel.getLatestVersion(scriptId);
  }
  
  // 比较版本差异
  async compareVersions(versionId1: string, versionId2: string): Promise<{
    version1: IVersion;
    version2: IVersion;
    diff: VersionDiff;
  }> {
    const [version1, version2] = await Promise.all([
      versionModel.findById(versionId1),
      versionModel.findById(versionId2)
    ]);
    
    if (!version1) {
      throw new Error('第一个版本不存在');
    }
    
    if (!version2) {
      throw new Error('第二个版本不存在');
    }
    
    if (version1.script_id !== version2.script_id) {
      throw new Error('两个版本不属于同一个脚本');
    }
    
    const diff = await versionModel.compareVersions(versionId1, versionId2);
    
    return {
      version1,
      version2,
      diff
    };
  }
  
  // 获取版本统计信息
  async getVersionStats(scriptId: string): Promise<{
    total_versions: number;
    first_version_date: Date;
    last_version_date: Date;
    authors: string[];
    version_frequency: Array<{
      date: string;
      count: number;
    }>;
  }> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    const stats = await versionModel.getVersionStats(scriptId);
    
    // 获取版本创建频率（按天统计）
    const frequencyResult = await versionModel.raw(
      `SELECT 
        DATE(created_at) as date,
        COUNT(*) as count
       FROM versions 
       WHERE script_id = $1 
       GROUP BY DATE(created_at) 
       ORDER BY date DESC 
       LIMIT 30`,
      [scriptId]
    );
    
    return {
      ...stats,
      version_frequency: frequencyResult.rows.map((row: any) => ({
        date: row.date,
        count: parseInt(row.count, 10)
      }))
    };
  }
  
  // 获取版本树（显示版本关系）
  async getVersionTree(scriptId: string): Promise<any[]> {
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      throw new Error('脚本不存在');
    }
    
    return await versionModel.getVersionTree(scriptId);
  }
  
  // 删除版本（仅允许删除最新版本，且不是唯一版本）
  async deleteVersion(versionId: string): Promise<boolean> {
    const version = await versionModel.findById(versionId);
    if (!version) {
      throw new Error('版本不存在');
    }
    
    // 检查是否是最新版本
    const latestVersion = await versionModel.getLatestVersion(version.script_id);
    if (!latestVersion || latestVersion.id !== versionId) {
      throw new Error('只能删除最新版本');
    }
    
    // 检查是否是唯一版本
    const versionCount = await versionModel.count({ script_id: version.script_id });
    if (versionCount <= 1) {
      throw new Error('不能删除脚本的唯一版本');
    }
    
    // 删除版本
    const deleted = await versionModel.delete(versionId);
    
    if (deleted) {
      // 更新脚本内容为最新版本
      const newLatestVersion = await versionModel.getLatestVersion(version.script_id);
      if (newLatestVersion) {
        await scriptModel.update(version.script_id, {
          content: newLatestVersion.content
        });
      }
    }
    
    return deleted;
  }
  
  // 标记版本（添加标签或注释）
  async tagVersion(versionId: string, message: string): Promise<IVersion | null> {
    const version = await versionModel.findById(versionId);
    if (!version) {
      throw new Error('版本不存在');
    }
    
    return await versionModel.update(versionId, { message });
  }
  
  // 获取版本内容预览
  async getVersionPreview(versionId: string, lines: number = 50): Promise<{
    version: IVersion;
    preview: string;
    total_lines: number;
  }> {
    const version = await versionModel.findById(versionId);
    if (!version) {
      throw new Error('版本不存在');
    }
    
    const contentLines = version.content.split('\n');
    const preview = contentLines.slice(0, lines).join('\n');
    
    return {
      version,
      preview,
      total_lines: contentLines.length
    };
  }
  
  // 检查版本完整性
  async validateVersionIntegrity(scriptId: string): Promise<{
    valid: boolean;
    issues: string[];
  }> {
    const issues: string[] = [];
    
    // 验证脚本是否存在
    const script = await scriptModel.findById(scriptId);
    if (!script) {
      issues.push('脚本不存在');
      return { valid: false, issues };
    }
    
    // 获取所有版本
    const versions = await versionModel.getVersionHistory(scriptId);
    
    if (versions.length === 0) {
      issues.push('脚本没有任何版本');
    }
    
    // 检查版本号是否连续
    const versionNumbers = versions.map(v => v.version).sort();
    for (let i = 1; i < versionNumbers.length; i++) {
      const current = versionNumbers[i].split('.').map(Number);
      const previous = versionNumbers[i - 1].split('.').map(Number);
      
      // 简单检查：版本号应该递增
      const currentNum = current[0] * 10000 + current[1] * 100 + current[2];
      const previousNum = previous[0] * 10000 + previous[1] * 100 + previous[2];
      
      if (currentNum <= previousNum) {
        issues.push(`版本号顺序异常: ${versionNumbers[i - 1]} -> ${versionNumbers[i]}`);
      }
    }
    
    // 检查内容哈希是否重复
    const contentHashes = versions.map(v => v.content_hash);
    const uniqueHashes = new Set(contentHashes);
    if (contentHashes.length !== uniqueHashes.size) {
      issues.push('存在重复的内容版本');
    }
    
    return {
      valid: issues.length === 0,
      issues
    };
  }
}